// handlers/SeriesHandler.js
const BaseHandler = require('./BaseHandler');
const fs = require('fs');
const path = require('path');
const {encodeRoutePath} = require("../util/url");
const {generateSha1ByBasename} = require("../util/hash");
const {getBasenameWithoutExt} = require("../util/file");


class SeriesHandler extends BaseHandler {
    async handle(req, res, dirPath) {
        try {
            if (!await this.fileExists(dirPath)) {
                return this.sendError(res, 404, 'Series directory not found');
            }

            // 读取目录内容
            const items = await fs.promises.readdir(dirPath, { withFileTypes: true });

            // 过滤视频文件
            const videoFiles = items
                .filter(item => item.isFile() && this.isVideoFile(item.name))
                .sort((a, b) => this.sortVideoFiles(a.name, b.name));

            // 读取子目录（剧集季）
            const subDirs = items
                .filter(item => item.isDirectory())
                .sort((a, b) => a.name.localeCompare(b.name));

            for (const videoFile of videoFiles) {
                const handler = this.server.handlers["video"];
                const route = generateSha1ByBasename(getBasenameWithoutExt(videoFile.name));
                // const route = path.join(path.basename(videoFile.parentPath), videoFile.name);
                // const encodedRoute = encodeRoutePath(route);

                videoFile.url = route;
                // console.log(`registering ${path.dirname(req.url)}/${route}`);
                // this.server.app.get(`${path.dirname(req.url)}/${route}`, async (req, res) => {
                //     try {
                //         await handler.handle(req, res, path.join(videoFile.parentPath, videoFile.name));
                //     } catch (error) {
                //         console.error(`Error handling route ${route}:`, error);
                //         res.status(500).json({
                //             error: 'Failed to process file',
                //             route: route
                //         });
                //     }
                // });
            }

            // 每个视频文件单独注册一个路由
            // videoFiles.forEach((videoFile, index) => {
            //     const handler = this.server.handlers["video"];
            //     const route = path.join(path.basename(videoFile.parentPath), videoFile.name);
            //     const encodedRoute = encodeRoutePath(route);
            //     console.log(`registering ${encodedRoute}`);
            //     this.server.app.get(`/${encodedRoute}`, async (req, res) => {
            //         try {
            //             await handler.handle(req, res, path.join(videoFile.parentPath, videoFile.name));
            //         } catch (error) {
            //             console.error(`Error handling route ${route}:`, error);
            //             res.status(500).json({
            //                 error: 'Failed to process file',
            //                 route: route
            //             });
            //         }
            //     });
            // });

            if (videoFiles.length === 0 && subDirs.length === 0) {
                return this.sendError(res, 404, 'No video files found in series directory');
            }

            // 生成剧集选择页面
            const html = this.generateSeriesHTML(
                path.basename(dirPath),
                videoFiles,
                subDirs,
                dirPath
            );

            res.setHeader('Content-Type', 'text/html; charset=utf-8');
            res.send(html);

        } catch (error) {
            console.error('Error reading series directory:', error);
            this.sendError(res, 500, 'Failed to process series directory');
        }
    }

    isVideoFile(filename) {
        const videoExtensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp'];
        const ext = path.extname(filename).toLowerCase();
        return videoExtensions.includes(ext);
    }

    sortVideoFiles(a, b) {
        // 提取数字进行自然排序（例如：第01集.mp4, 第02集.mp4）
        const numA = this.extractEpisodeNumber(a);
        const numB = this.extractEpisodeNumber(b);

        if (numA !== null && numB !== null) {
            return numA - numB;
        }

        return a.localeCompare(b);
    }

    extractEpisodeNumber(filename) {
        const match = filename.match(/(\d+)/);
        return match ? parseInt(match[1]) : null;
    }

    generateSeriesHTML(seriesName, videoFiles, subDirs, basePath) {
        let html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${this.escapeHtml(seriesName)} - 剧集目录</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
            line-height: 1.6; 
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        .header .back-link {
            color: #ecf0f1;
            text-decoration: none;
            font-size: 0.9em;
        }
        .content {
            padding: 30px;
        }
        .section {
            margin-bottom: 30px;
        }
        .section h2 {
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .file-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
        }
        .file-item, .dir-item {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
            transition: all 0.3s ease;
            text-decoration: none;
            color: inherit;
        }
        .file-item:hover, .dir-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            background: #e3f2fd;
            border-color: #2196f3;
        }
        .file-icon, .dir-icon {
            font-size: 2em;
            margin-bottom: 10px;
            color: #3498db;
        }
        .file-name, .dir-name {
            font-weight: 500;
            word-break: break-word;
        }
        .file-size {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }
        .no-files {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 40px;
        }
        @media (max-width: 768px) {
            .file-grid {
                grid-template-columns: 1fr;
            }
            .header h1 {
                font-size: 2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>${this.escapeHtml(seriesName)}</h1>
            <a href="javascript:history.back()" class="back-link">← 返回上级目录</a>
        </div>
        <div class="content">`;

        // 添加子目录（剧集季）
        if (subDirs.length > 0) {
            html += `
            <div class="section">
                <h2>📁 剧集季</h2>
                <div class="file-grid">`;

            subDirs.forEach(dir => {
                const dirUrl = encodeURIComponent(dir.name);
                html += `
                    <a href="${dirUrl}" class="dir-item">
                        <div class="dir-icon">📁</div>
                        <div class="dir-name">${this.escapeHtml(dir.name)}</div>
                    </a>`;
            });

            html += `
                </div>
            </div>`;
        }

        // 添加视频文件
        if (videoFiles.length > 0) {
            html += `
            <div class="section">
                <h2>🎬 剧集列表 (${videoFiles.length}个文件)</h2>
                <div class="file-grid">`;

            for (const file of videoFiles) {
                const fileUrl = file.url;
                const fileSize = this.formatFileSize(this.getFileSizeSync(path.join(basePath, file.name)));

                html += `
                    <a href="${fileUrl}#~:~hint=${file.name}" class="file-item">
                        <div class="file-icon">🎥</div>
                        <div class="file-name">${this.escapeHtml(file.name)}</div>
                        <div class="file-size">${fileSize}</div>
                    </a>`;
            }

            html += `
                </div>
            </div>`;
        }

        html += `
        </div>
    </div>
    
    <script>
        // 添加点击统计（可选功能）
        document.addEventListener('DOMContentLoaded', function() {
            const links = document.querySelectorAll('.file-item, .dir-item');
            links.forEach(link => {
                link.addEventListener('click', function(e) {
                    const fileName = this.querySelector('.file-name, .dir-name').textContent;
                    console.log('播放剧集:', fileName);
                    // 这里可以添加统计代码
                });
            });
        });
    </script>
</body>
</html>`;

        return html;
    }

    getFileSizeSync(filePath) {
        try {
            const stats = fs.statSync(filePath);
            return stats.size;
        } catch {
            return 0;
        }
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, m => map[m]);
    }
}

module.exports = SeriesHandler;